package sz.com.postoffice.jxyzwgcase.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class ExportWord {
	private static Logger logger = LoggerFactory.getLogger(ExportWord.class);
	private Configuration configuration;
	private String encoding;
	private String exportPath = "D:\\test\\";

	/**
	 * 构造函数 配置模板路径
	 * 
	 * @param encoding
	 */
	public ExportWord(String encoding) {
		this.encoding = encoding;
		configuration = new Configuration();
		configuration.setDefaultEncoding(encoding);
		configuration.setClassForTemplateLoading(this.getClass(), "/templates");
	}

	/**
	 * 获取模板
	 * 
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public Template getTemplate(String name) throws Exception {
		return configuration.getTemplate(name);
	}

	/**
	 * 导出word文档到指定目录
	 * 
	 * @param fileName
	 * @param tplName
	 * @param data
	 * @throws Exception
	 */
	public void exportDocFile(String fileName, String tplName, Map<String, Object> data) throws Exception {
		logger.debug("导出word到D:\test");
		// 如果目录不存在，则创建目录
		File exportDirs = new File(exportPath);
		if (!exportDirs.exists()) {
			exportDirs.mkdirs();
		}
		Writer writer = new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(exportPath + fileName), encoding));
		getTemplate(tplName).process(data, writer);
	}

	/**
	 * 导出word文档到客户端
	 * 
	 * @param response
	 * @param fileName
	 * @param tplName
	 * @param data
	 * @throws Exception
	 */
	public void exportDoc(HttpServletResponse response, String tplName, Map<String, Object> data) throws Exception {
		// 把本地文件发送给客户端
		Template template = getTemplate(tplName);
		response.setCharacterEncoding("UTF-8");
		response.reset(); // 非常重要
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment; filename=data.xls");
		// 将模板和数据模型合并生成文件
		Writer out = response.getWriter();
		// 生成文件
		template.process(data, out);
		// 关闭流
		out.flush();
		out.close();
	}
}
